package com.mscenter.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import com.mscenter.model.ApplicationInfo;
import com.mscenter.model.ApplicationInstanceInfo;
import com.mscenter.service.MsCenterService;

@Service
public class MsCenterServiceImpl implements MsCenterService {

	@Autowired
	private DiscoveryClient discoveryClient;

	@Override
	public List<ApplicationInfo> listAppInfos() {
		/**
		 * 微服务信息列表
		 */
		List<ApplicationInfo> appInfos = new ArrayList<ApplicationInfo>();
		ApplicationInfo appInfo = null;
		//获取注册在eureck上所有的实例微服务
		List<ServiceInstance> list = discoveryClient.getInstances("STORES");
		for (String s : discoveryClient.getServices()) {
			appInfo = new ApplicationInfo();
			//微服务的实例集合
			Set<ApplicationInstanceInfo> applicationInstanceInfos = new HashSet<ApplicationInstanceInfo>();
			//微服务实例对象
			ApplicationInstanceInfo applicationInstanceInfo;
			System.out.println("services " + s);
			appInfo.setApplicationName(s);
			List<ServiceInstance> serviceInstances = discoveryClient.getInstances(s);
			for (ServiceInstance si : serviceInstances) {
				applicationInstanceInfo = new ApplicationInstanceInfo();
				System.out.println("    services:" + s + ":getHost()=" + si.getHost());
				System.out.println("    services:" + s + ":getPort()=" + si.getPort());
				System.out.println("    services:" + s + ":getServiceId()=" + si.getServiceId());
				System.out.println("    services:" + s + ":getUri()=" + si.getUri());
				System.out.println("    services:" + s + ":getMetadata()=" + si.getMetadata());
				applicationInstanceInfo.setInstanceId(si.getServiceId());	
				applicationInstanceInfo.setIpAddress(si.getHost());
				applicationInstanceInfo.setPort(si.getPort()+"");
				applicationInstanceInfo.setSwaggerUrl("http://localhost:10001/"+ s +"/swagger-ui.html");
				applicationInstanceInfo.setStatus(si.isSecure() ? "critical" : "success");
				applicationInstanceInfos.add(applicationInstanceInfo);
			}
			appInfo.setDescription(s); 
			appInfo.setApplicationInstances(applicationInstanceInfos);
			appInfo.setRepoConfig("http://localhost:8560/"+ s +"-master.yml");
			appInfo.setZuulSwaggerUrl("http://localhost:10001/"+ s +"/swagger-ui.html");
			appInfo.setApplicationInstances(applicationInstanceInfos);
			appInfos.add(appInfo);
		}
		System.out.println(list.size());
		if (list != null && list.size() > 0) {
			System.out.println(list.get(0).getUri());
		}
		return appInfos;
	}

}
